package com.duoqin.chat.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.duoqin.chat.Chat;
import com.duoqin.guard.ChatContacts;
import com.duoqin.guard.GuardServiceManager;
import com.duoqin.chat.IDuoqinChatCallback;
import com.duoqin.common.ui.AbsActivity;
import com.duoqin.common.utils.NetworkUtils;
import com.duoqin.common.widget.RecyclerViewDivider;
import com.duoqin.syncassistant.R;
import com.duoqin.syncassistant.SyncAssistantApplication;
import com.duoqin.syncassistant.data.ContactsResponse;

import java.util.ArrayList;
import java.util.List;

public class ChatListActivity extends AbsActivity {
    public static final String SHARED_PREF_KEY_SHALL_UPDATE_CONTACTS = "shall_update_contacts";

    private final int REQUEST_CHAT = 0;

    private List<ContactsResponse.ListBean> mContactsList = new ArrayList<>();

    private ChatListAdapter mChatListAdapter;
    private RecyclerView mListView;
    private RecyclerViewDivider mRecyclerViewDivider;

    private IDuoqinChatCallback mCallback = new IDuoqinChatCallback.Stub() {
        public void messageReceived(String chatId) {
            Log.i(TAG, "onMessageReceived chatId = " + chatId);
            mHandler.sendEmptyMessage(MSG_UPDATE_UI);
        }

        public void failureReport(String status) {
            Log.i(TAG, "failureReport status = " + status);
        }
    };

    private static final int MSG_UPDATE_UI = 0;
    @SuppressLint("HandlerLeak")
    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_UI: {
                    if (mChatListAdapter != null) {
                        mChatListAdapter.notifyDataSetChanged();
                    }
                    break;
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        setContentView(R.layout.activity_chat_list);
        setupTitle(getString(R.string.duoqin_chat));

        mListView = findViewById(R.id.chat_list);
        mListView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerViewDivider = new RecyclerViewDivider(this,
                LinearLayoutManager.VERTICAL, R.drawable.duoqin_list_divider_inset,
                getResources().getDimensionPixelOffset(R.dimen.duoqin_dimen_list_divider_height),
                new ArrayList<Integer>());
        mListView.addItemDecoration(mRecyclerViewDivider);
        mChatListAdapter = new ChatListAdapter();
        mListView.setAdapter(mChatListAdapter);

        if (SyncAssistantApplication.getsInstance().hasLogin()) {
            getChatContacts();
            Intent intent = new Intent("com.duoqin.remoteLocating");
            intent.setPackage("com.duoqin.remoteservice");
            intent.putExtra("restart", true);
            sendBroadcast(intent);
        }

        GuardServiceManager.getInstance(this, mCallback, null);
    }

    protected void setupTitle(String title) {
        mToolbar = findViewById(R.id.toolbar);
        mToolbar.setTitle(title);
    }

    private void getChatContacts() {
        List<ChatContacts> chatContactsList = ChatContacts.getChatContacts(getContentResolver());
        mContactsList.clear();
        if (chatContactsList.size() > 0) {
            for (ChatContacts chatContacts : chatContactsList) {
                ContactsResponse.ListBean bean = new ContactsResponse.ListBean();
                bean.setName(chatContacts.name);
                bean.setOpenId(chatContacts.openId);
                bean.setImg(chatContacts.img);
                mContactsList.add(bean);
            }
            mHandler.sendEmptyMessage(MSG_UPDATE_UI);
        } else {
            Log.w(TAG, "getChatContacts 0");
            finish();
        }
    }

    private class ContactsViewHolder extends RecyclerView.ViewHolder {
        View itemView;
        ImageView avatarIV;
        TextView nameTV;
        TextView unreadCountTV;

        ContactsViewHolder(View itemView) {
            super(itemView);
            this.itemView = itemView;
            avatarIV = itemView.findViewById(R.id.avatar);
            nameTV = itemView.findViewById(R.id.name);
            unreadCountTV = itemView.findViewById(R.id.unread_count);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (int) v.getTag();
                    if (position < mContactsList.size()) {
                        Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
                        intent.putExtra(ChatActivity.INTENT_EXTRA_OPEN_ID,
                                mContactsList.get(position).getOpenId());
                        intent.putExtra(ChatActivity.INTENT_EXTRA_NAME,
                                mContactsList.get(position).getName());
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivityForResult(intent, REQUEST_CHAT);
                    }
                }
            });
        }
    }

    private class ChatListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View convertView = getLayoutInflater().inflate(R.layout.list_item_contacts,
                    parent, false);
            return new ContactsViewHolder(convertView);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            ContactsViewHolder contactsViewHolder = (ContactsViewHolder) holder;
            contactsViewHolder.itemView.setTag(position);
            contactsViewHolder.nameTV.setText(mContactsList.get(position).getName());
            int count = Chat.getUnreadChatCount(getContentResolver(),
                    mContactsList.get(position).getOpenId());
            if (count > 0) {
                contactsViewHolder.unreadCountTV.setText(getString(R.string.unread_message_count, count));
                contactsViewHolder.unreadCountTV.setVisibility(View.VISIBLE);
            } else {
                contactsViewHolder.unreadCountTV.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return mContactsList != null ? mContactsList.size() : 0;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        GuardServiceManager.registerChatCallback(mCallback);
        if (!NetworkUtils.isConnected(getApplicationContext())) {
            Toast.makeText(getApplicationContext(),
                    R.string.network_error_no_network, Toast.LENGTH_SHORT).show();
        } else {
            if (SyncAssistantApplication.getsInstance().hasLogin()) {
                if (SyncAssistantApplication.getsInstance().getSharedPreference()
                        .getBoolean(SHARED_PREF_KEY_SHALL_UPDATE_CONTACTS, true)) {
                    getChatContacts();
                }
            } else {
                Log.w(TAG, "not login! can not chat");
                finish();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        GuardServiceManager.registerChatCallback(null);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult resultCode = " + resultCode
                + "; requestCode = " + requestCode);
        if (Activity.RESULT_OK != resultCode) return;
        if (REQUEST_CHAT == requestCode) {
            mHandler.sendEmptyMessage(MSG_UPDATE_UI);
        }
    }
}
